package org.jeecg.modules.runner;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.codehaus.jettison.json.JSONObject;
import org.codehaus.jettison.json.JSONTokener;
import org.jeecg.boot.starter.rabbitmq.core.BaseRabbiMqHandler;
import org.jeecg.boot.starter.rabbitmq.listenter.MqListener;
import org.jeecg.common.annotation.RabbitComponent;
import org.jeecg.common.base.BaseMap;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.device.DeviceContainer;
import org.jeecg.modules.device.TigDeviceShadow;
import org.jeecg.modules.driver.DriverCommandList;
import org.jeecg.modules.device.Device;
import org.jeecg.modules.entity.TigerDeviceLog;
import org.jeecg.modules.service.DeviceService;
import org.jeecg.modules.service.ITigDeviceService;
import org.jeecg.modules.service.ITigerDeviceLogService;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@Slf4j
@RabbitComponent(value = "warnningAnalysisListener")
public class WarnningAnalysisListener extends BaseRabbiMqHandler<BaseMap> {

    @Autowired
    DeviceContainer deviceContainer;

    @Autowired
    DeviceService deviceService;

    @Autowired
    ITigerDeviceLogService iTigerDeviceLogService;

    @Autowired
    ITigDeviceService iTigDeviceService;

    @Autowired
    RedisUtil redisUtil;


    @RabbitListener(queues = "warningData")
    public void onMessage(BaseMap baseMap, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        super.onMessage(baseMap, deliveryTag, channel, new MqListener<BaseMap>() {
            @Override
            public void handler(BaseMap map, Channel channel) {
                try {
                    String deviceId = map.get("deviceId");
                    String dataStr = map.get("data");
                    String cmd = map.get("cmd");
                    if (deviceId == null) return;

                    //判断接收到处理消息的时候设备是否已经从数据库删除了
                    if (iTigDeviceService.getById(deviceId) == null){
                        log.error("warningData Error Msg:device id = " + deviceId + "has been delete,you can't get it again");
                        return;
                    }

                    TigDeviceShadow sd = deviceContainer.getShadowDevice(deviceId);
                    if(sd == null) return;
                    Device d = sd.getDevice();
                    d.setShadow(new JSONObject(new JSONTokener(dataStr)));
                    String warningMsg = "";
                    Map<Integer,String> mapWaning;
                    if (cmd.equals(DriverCommandList.D_deviceWanringChannel)) {
                        warningMsg = d.getNewChannelWarning();
                        if (warningMsg != null && !warningMsg.isEmpty()) {
                            generateDeviceWarningLog(d, "7",warningMsg);//32路开关异常
                        }
                    } else if (cmd.equals(DriverCommandList.D_deviceWarningDevice)) {
                        mapWaning = d.getNewDeviceWarning();
                        mapWaning.forEach((key, value) -> {
                            try {
                                generateDeviceWarningLog(d, String.valueOf(key+1),value);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        });
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void generateDeviceWarningLog(Device d, String warningType,String warningMsg) throws Exception {
        log.info("==============generateDeviceWarningLog===============");
        TigerDeviceLog log = new TigerDeviceLog();
        Date date = new Date(Long.parseLong(d.getShadow().getString("cmdTime")));
        //----------------生成日志---------------------------------------------------
        log.setName(d.getShadow().getJSONObject("baseinfo").getString("name"));
        log.setDeviceId(d.getId());
        log.setLogTime(date);
        log.setContent(warningMsg);
        log.setLogCategory("1");//预警类型
        log.setHandleStatus("0");//未处理
        log.setLogType(warningType);
        log.setSysOrgCode(deviceContainer.getShadowDevice(d.getId()).getTigDeviceEntity().getSysOrgCode());
        iTigerDeviceLogService.save(log);
        //发送通知消息到部门负责人
        String name = "";
        if (warningType.compareTo("7") == 0){
            name = "设备【" + d.getShadow().getJSONObject("baseinfo").getString("name") + "】通道异常告警消息";
        }
        else{
            name = "设备【" + d.getShadow().getJSONObject("baseinfo").getString("name") + "】告警消息";
        }
        String anMsg = "设备【" + d.getShadow().getJSONObject("baseinfo").getString("name") + "】" + warningMsg;
        deviceService.sendAnnouncementToDepartment(d.getId(), name,anMsg);
        //redis设备错误类型计数
        int typeCount = 0;
        if(redisUtil.get("device_warning_" + warningType + "type" + d.getId()) != null){
            typeCount = Integer.parseInt(String.valueOf(redisUtil.get("device_warning_" + warningType + "type" + d.getId())));
            typeCount++;
        }
        else {
            typeCount =deviceService.getWarningCountByDeviceId(d.getId(),Integer.parseInt(warningType));
        }
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String transformDate = simpleDateFormat.format(date);
        redisUtil.set("device_warning_time"+d.getId(),transformDate);
        redisUtil.set("device_warning_" + warningType + "type" + d.getId(),typeCount);
    }
}
